﻿using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HandyControlProject5
{
    public class WordToPdfHelper : IDisposable
    {

        dynamic wps;

        public WordToPdfHelper()
        {
            //创建wps实例，需提前安装wps
            Type type = Type.GetTypeFromProgID("KWps.Application");
            wps = Activator.CreateInstance(type);
        }

        /// <summary>
        /// Word转PDF
        /// </summary>
        /// <param name="wordPath">Wps文件路径</param>
        /// <param name="pdfPath">Pdf文件路径</param>
        /// <returns></returns>
        public void ToPdf(string wordPath, string pdfPath = null)
        {
            try
            {
                if (wordPath == null)
                {
                    throw new ArgumentNullException("wpsFilename");
                }
                if (pdfPath == null)
                {
                    pdfPath = Path.ChangeExtension(wordPath, "pdf");
                }
                Console.WriteLine(string.Format(@"正在转换 [{0}] -> [{1}]", wordPath, pdfPath));

                //用wps 打开word不显示界面
                dynamic doc = wps.Documents.Open(wordPath, Visible: false);
                //doc 转pdf 
                doc.ExportAsFixedFormat(pdfPath, WdExportFormat.wdExportFormatPDF);
                //设置隐藏菜单栏和工具栏
                //wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public void Dispose()
        {
            if (wps != null) { wps.Quit(); }
        }
    }

}
